package com.cq.hd.system.config;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.cq.hd.common.response.Throw;
import com.cq.hd.common.utils.LocalDateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.Date;

@Slf4j
@Component
public class OssConfig {

    @Value("${oss.aliyun.host}")
    private String host;

    @Value("${oss.aliyun.endPoint}")
    private String endPoint;

    @Value("${oss.aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.aliyun.accessKeySecret}")
    private String accessKeySecret;

    @Value("${oss.aliyun.bucketName}")
    private String bucketName;

    @Value("${oss.aliyun.path}")
    private String path;

    private final static String SLASH = "/";

    private final static String DROP = ".";

    private final static String YYYYMMDDHHMMSSSSS = "yyyyMMddHHmmssSSS";

    public String uploadFile(MultipartFile file, String uploadPath, String fileName) {
        if (file == null || file.isEmpty() || StringUtils.isEmpty(file.getOriginalFilename())) {
            return "";
        }

        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(DROP) + 1);

        if (StringUtils.isEmpty(fileName)) {
            fileName = LocalDateUtil.toLocalDateTimeToString(LocalDateTime.now(), YYYYMMDDHHMMSSSSS) + DROP + fileExtension;
        }
        try {
            return uploadFile(file.getInputStream(), fileExtension, uploadPath, fileName);
        } catch (Exception e) {
            Throw.isBusinessException("上传文件失败");
        }

        return "";
    }

    public String uploadFile(InputStream input, String fileType, String uploadPath, String fileName) {
        fileName = path + uploadPath + SLASH + fileName;
        // 默认null
        String urls = null;
        // 最终返回的路径
        String saveUrl = null;
        OSSClient ossClient = null;
        try {
            ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
            // 创建上传Object的Metadata
            ObjectMetadata meta = new ObjectMetadata();
            // 设置上传内容类型
            meta.setContentType(contentType(fileType));
            // 被下载时网页的缓存行为
            meta.setCacheControl("no-cache");
            PutObjectRequest request = new PutObjectRequest(bucketName, fileName, input, meta);
            // 创建上传请求
            ossClient.putObject(request);
            // 设置Object权限
            boolean found = ossClient.doesObjectExist(bucketName, fileName);
            if (found) {
                ossClient.setObjectAcl(bucketName, fileName, CannedAccessControlList.PublicRead);
            }
            Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
            URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);
            // 对返回的签名url处理获取最终展示用的url
            urls = url.toString();
            String[] strs = urls.split("\\?");
            for (int i = 0, len = strs.length; i < len; i++) {
                saveUrl = strs[0];
            }

            // 替换图片访问的域名
            if (!StringUtils.isEmpty(saveUrl)) {
                String[] splitSaveUrl = saveUrl.split("\\.com");
                saveUrl = host + splitSaveUrl[1];
            }
            log.info("OSS上传成功访问的地址" + saveUrl);
        } catch (OSSException oe) {
            log.error("OSSException异常");
            oe.printStackTrace();
            throw new RuntimeException("上传文件失败");
        } catch (ClientException ce) {
            log.error("ClientException异常");
            ce.printStackTrace();
            throw new RuntimeException("上传文件失败");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("上传文件失败");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return saveUrl;
    }

    public static String contentType(String fileType) {
        fileType = fileType.toLowerCase();
        String contentType = "";
        switch (fileType) {
            case "bmp":
                contentType = "image/bmp";
                break;
            case "gif":
                contentType = "image/gif";
                break;
            case "png":
            case "jpeg":
            case "jpg":
                contentType = "image/jpeg";
                break;
            case "html":
                contentType = "text/html";
                break;
            case "txt":
                contentType = "text/plain";
                break;
            case "vsd":
                contentType = "application/vnd.visio";
                break;
            case "ppt":
            case "pptx":
                contentType = "application/vnd.ms-powerpoint";
                break;
            case "doc":
            case "docx":
                contentType = "application/msword";
                break;
            case "xml":
                contentType = "text/xml";
                break;
            case "mp4":
                contentType = "video/mp4";
                break;
            default:
                contentType = "application/octet-stream";
                break;
        }
        return contentType;
    }


}
